package MapAndSet.HashBucket;

public class HashBucket {//哈系桶是哈希查找的关键

    static class Node{
        public int key;
        public int value;
        public Node next;
        public Node(int key,int value){
            this.key = key;
            this.value = value;
        }
    }

    public Node[] array;

    public int usedSize;

    public HashBucket() {
        array = new Node[10];
    }

    public void putLast (int key,int value){//尾插法，这里的尾差指的是，在表对应的位置上，对链表结构进行尾插
        int index = key % array.length;
        Node node = new Node(key,value);
        if(array[index] == null){//第一次插入
            array[index] = node;
            usedSize++;
            if(loadFactor() >=0.75){
                resize();
            }
            return;
        }
        Node cur = array[index];//若不是第一次插入,则进行尾插
        while(cur.next!=null){//尾插
            cur = cur.next;
        }

        cur.next = node;
        usedSize++;

        if(loadFactor() >= 0.75){
            resize();
        }
    }

    public void putFirst (int key , int value) {
        int index = key % array.length;
        Node node = new Node(key,value);
        Node cur = array[index];
        //先遍历一遍链表结构，检查是否存在当前的key
        while(cur!=null){
            if(cur.key==key){
                cur.value = value;//若存在当前key，则把当前的value更新掉
                return;
            }
        }
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if(loadFactor() >= 0.75){
            resize();
        }
    }

    private double loadFactor() {//算负载因子
        return usedSize*1.0/array.length;
    }

    private void resize(){//如果负载因子大于0.75就对表进行扩容
        Node[] tempArray = new Node[array.length*2];

        for (int i = 0; i < array.length; i++) {//遍历原来的表
            Node cur = array[i];
            while(cur != null) {//找到非空的表位
                Node curNext = cur.next;//先记录下表位的next，后续会对next进行修改，所以要进行next的备份
                int newIndex = cur.key % tempArray.length;//算出表位链表上的key对应新表的位置，如13%20=13,就找到13位置
                cur.next = tempArray[newIndex];//头插到新表里,这样就把key：13从链表中分离出来了
                tempArray[newIndex] = cur;
                cur = curNext;//遍历表位的链表
            }
        }

        array=tempArray;//覆盖旧表
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur!=null){
            if(cur.key == key){
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
